<template>
  <div class="app-container">
    <el-card header="入库单基本信息">
      <el-form label-width="108px" :model="form" ref="receiptForm" :rules="rules">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="入库单号" prop="billsId">
              <el-input v-model="form.billsId" placeholder="入库单号" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据日期" prop="checkDate">
              <el-date-picker
                v-model="form.checkDate"
                type="date"
                placeholder="选择单据日期"
                value-format="yyyy-MM-dd"
                style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="制单人" prop="creatorName">
              <el-input v-model="form.creatorName" placeholder="制单人" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="制单时间" prop="createTime">
              <el-input v-model="form.createTime" placeholder="制单时间" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="单据状态" prop="billsStateName">
              <el-input v-model="form.billsStateName" placeholder="单据状态" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="往来单位" prop="billsCd">
              <el-select style="width: 100%" v-model="form.billsCd" placeholder="请选择往来单位" clearable filterable>
                <el-option v-for="item in merchantList" :key="item.id" :label="item.customerName" :value="item.customerCode"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form-item label="入库类型" prop="billsType">
              <el-radio-group v-model="form.billsType" @change="generateOrderNo">
                <el-radio-button
                  v-for="item in wms_receipt_type"
                  :key="item.value"
                  :label="item.value"
                >{{ item.label }}
                </el-radio-button
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="备注" prop="remarks1">
              <el-input
                v-model="form.remarks1"
                placeholder="这里填写备注"
                rows="4"
                maxlength="100"
                type="textarea"
                show-word-limit="show-word-limit"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="总件数" prop="totalPackages">
              <el-input v-model="form.totalPackages" placeholder="总件数" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总数量" prop="totalQuantity">
              <el-input v-model="form.totalQuantity" placeholder="总数量" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-if="form.billsState === '3'">
          <el-col :span="12">
            <el-form-item label="签字人" prop="secondUser">
              <el-input v-model="form.secondUser" placeholder="签字人" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签字信息" prop="remarks2">
              <el-input v-model="form.remarks2" placeholder="签字信息" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" v-if="form.billsState === '4'">
          <el-col :span="24">
            <el-form-item label="作废信息" prop="remarks1">
              <el-input v-model="form.remarks1" placeholder="作废信息" :disabled="true" type="textarea" rows="2"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card header="商品明细" class="mt10">
      <el-button type="primary" size="default" @click="showAddItem">添加商品</el-button>
      <el-button type="success" size="default" @click="goToIn">提交</el-button>
      <el-table :data="detailList" border class="mt20">
        <el-table-column show-overflow-tooltip type="index" label="行号" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugId" label="编码" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugName" label="名称" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugCd" label="厂家" align="center"width="200"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugPZWH" label="批准文号" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugGg" label="规格" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugDw" label="单位" align="center"></el-table-column>
        <el-table-column show-overflow-tooltip prop="drugNum" label="数量" align="center" width="150">
          <template #default="{row}">
            <el-input-number v-model="row.drugNum" :min="1" :max="9999" @change="calculateTotals"></el-input-number>
          </template>
        </el-table-column>

        <el-table-column show-overflow-tooltip prop="drugBatchNo" label="批次号" align="center">
          <template #default="{row}">
            <el-input v-model="row.drugBatchNo" placeholder="批次号（可选）"></el-input>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="drugPd" label="生产日期" align="center"width="150">
          <template #default="{row}">
            <el-date-picker v-model="row.drugPd" type="date" placeholder="生产日期（可选）" value-format="yyyy-MM-dd"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="drugExp" label="有效期" align="center"width="150">
          <template #default="{row}">
            <el-date-picker v-model="row.drugExp" type="date" placeholder="有效期（可选）" value-format="yyyy-MM-dd"></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <SkuSelect :show.sync="drawer" @getData="getList"/>
  </div>
</template>

<script>
import SkuSelect from './alterDocument.vue'
import {getAllWarehouseList} from "@/api/index/yxl";//获取仓库
import {
  queryAllList,//往来单位
  buyStoreOver,//完成入库
  buyStoreListDetail,//获取单据详情
} from '@/api/storage/buyStore'
export default {
  name: 'outBills',
  components: {
    SkuSelect
  },
  data() {
    return {
      drawer: false,
      form: {
        billsId: '',//入库单号
        checkDate: '',//单据日期
        creatorName: '',//创建人
        createTime: '',//创建时间
        stoId: '',//仓库
        billsState: '0',//单据状态（0-未收货）
        billsStateName: '未收货',//单据状态名称
        billsType: 'PurchaseWareHouseIn',//入库类型
        billsCd: '',//供应商
        remarks1: '',//备注
        totalPackages: 0,//总件数
        totalQuantity: 0,//总数量
      },
      wms_receipt_type: [
        { label: '采购入库', value: 'PurchaseWareHouseIn'},
        { label: '生产入库', value: 'ProduceWareHouseIn'},
        { label: '退货入库', value: 'ReturnWareHouseIn'},
        { label: '调拨入库', value: 'AllocateWareHouseIn'},
        { label: '赠品入库', value: 'GiftHouseIn'},
        { label: '其他入库', value: 'OtherHouseIn'}
      ],
      detailList: [],//table
      warehouseList: [],//仓库
      merchantList: [],//供应商
      rules: {
        checkDate: [
          {required: true, message: '请选择单据日期', trigger: 'change'},
        ],
        billsType: [
          {required: true, message: '请选择入库类型', trigger: 'blur'},
        ],
        billsCd: [
          {required: true, message: '请选择往来单位', trigger: 'blur'},
        ]
      }
    }
  },
  created() {
    this.getSelect();//获取仓库
    this.getCDs();//获取往来单位

    // 检查是否有billsId参数（编辑模式）
    if (this.$route.query.billsId) {
      this.loadBillsData(this.$route.query.billsId);
    } else {
      this.generateOrderNo();//生成单号
      this.initFormData();//初始化表单数据
    }
  },
  methods: {
    //初始化表单数据
    initFormData() {
      // 设置创建人（从store中获取当前登录用户名）
      this.form.creatorName = this.$store.getters.name || '系统管理员';

      // 设置创建时间和单据日期为当前时间
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');

      const currentDate = `${year}-${month}-${day}`;
      const currentDateTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

      this.form.checkDate = currentDate;
      this.form.createTime = currentDateTime;
    },
    //获取往来单位
    getCDs(){
      queryAllList().then(res=>{
        this.merchantList = res.data;
      })
    },
    //随机生成单号
    generateOrderNo() {
      const timestamp = new Date().getTime();
      const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');

      // 根据入库类型设置前缀
      let prefix = '';
      switch(this.form.billsType) {
        case 'PurchaseWareHouseIn': // 采购入库
          prefix = 'CR';
          break;
        case 'ProduceWareHouseIn': // 生产入库
          prefix = 'SR';
          break;
        case 'OtherHouseIn': // 其他入库
          prefix = 'QR';
          break;
        case 'ReturnWareHouseIn': // 退货入库
          prefix = 'TR';
          break;
        case 'AllocateWareHouseIn': // 调拨入库
          prefix = 'DR';
          break;
        case 'GiftHouseIn': // 赠品入库
          prefix = 'ZR';
          break;
        default:
          prefix = 'RK'; // 默认入库
      }
      this.form.billsId = `${prefix}${timestamp}${randomNum}`;
    },
    //完成入库操作
    goToIn(){
      // 检查是否有商品明细
      if (this.detailList.length === 0) {
        this.$message.error('请添加入库商品明细');
        return;
      }

      this.$confirm('确定完成提交吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$refs.receiptForm.validate((valid) => {
          if(valid){
            let data = {
              ...this.form,
              StoID: this.form.stoId, // 映射仓库ID字段名
              userId: this.$store.getters.userId || 'admin', // 用户ID
              Remarks1: this.form.remarks1, // 备注1
              inDetailList: this.detailList
            }

            // 调试日志：检查数据传递
            console.log('提交入库单数据:', data);
            console.log('仓库ID映射:', {
              'form.stoId': this.form.stoId,
              'data.StoID': data.StoID
            });
            buyStoreOver(data).then(res=>{
              this.$message.success(res.msg);
              this.$router.push({
                path: "/wms/receive/index",
              });
            }).catch(err => {
              this.$message.error('入库失败：' + (err.response?.data?.msg || err.message));
            })
          }else{
            return false
          }
        })
      }).catch(() => {
        this.$message.info('取消入库');
      });
    },
    //仓库下拉获取
    getSelect() {
      getAllWarehouseList().then(res => {
        this.warehouseList = res.data;
      })
    },
    //打开商品选中
    showAddItem() {
      this.drawer = true;
    },
    getList(selectedItems) {
      // 过滤掉已经存在的商品
      const newItems = selectedItems.filter(item =>
        !this.detailList.some(existing => existing.code === item.productCode)
      );

      // 将新商品添加到明细列表
      this.detailList = [
        ...this.detailList,
        ...newItems.map(item => {
          return {
            drugId: item.productCode,
            drugName: item.productName,
            drugGg: item.productSpec,
            drugPZWH: item.approvalNum || '', // 批准文号 (正确字段名，对应后端JsonProperty)
            drugBatchNo: '', // 批次号
            drugNum: 1, // 数量
            drugCd: item.manufacturer || '', // 生产厂家
            drugExp: '', // 有效期
            drugPd: '', // 生产日期·
            drugDw: item.unitName // 单位
          };
        })
      ];

      if (newItems.length < selectedItems.length) {
        this.$message.warning('部分商品已存在，未重复添加');
      }

      // 计算总件数和总数量
      this.calculateTotals();
    },
    //计算总件数和总数量
    calculateTotals() {
      let totalPackages = 0;
      let totalQuantity = 0;

      this.detailList.forEach(item => {
        // 总件数累加（假设每个商品的件数为1，如果有drugJsNum字段可以使用）
        totalPackages += 1;

        // 总数量累加
        if (item.drugNum && !isNaN(item.drugNum)) {
          totalQuantity += parseFloat(item.drugNum);
        }
      });

      this.form.totalPackages = totalPackages;
      this.form.totalQuantity = totalQuantity;
    },
    //删除
    handleDelete(row) {
      const index = this.detailList.indexOf(row);
      if (index !== -1) {
        this.detailList.splice(index, 1);
        this.$message.success('删除成功');
        // 重新计算总件数和总数量
        this.calculateTotals();
      }
    },
    //加载入库单数据（编辑模式）
    loadBillsData(billsId) {
      buyStoreListDetail(billsId).then(res => {
        if (res.code === 200 && res.data) {
          // 填充表单数据
          this.form = {
            billsId: res.data.billsId,
            checkDate: res.data.checkDate,
            creatorName: res.data.creatorName,
            createTime: res.data.createTime ? res.data.createTime.replace(/T/, ' ').substr(0, 19) : '',
            stoId: res.data.stoId || res.data.StoID, // 兼容不同的字段名
            billsState: res.data.billsState,
            billsStateName: this.getBillsStateName(res.data.billsState),
            billsType: res.data.billsType,
            billsCd: res.data.billsCd,
            remarks1: res.data.remarks1 || res.data.Remarks1, // 兼容不同的字段名
            totalPackages: res.data.totalPackages || 0,
            totalQuantity: res.data.totalQuantity || 0,
            secondUser: res.data.secondUser || res.data.SecondUser || '', // 兼容不同的字段名
            remarks2: res.data.remarks2 || res.data.Remarks2 || '', // 兼容不同的字段名
          };

          // 填充明细数据，确保字段映射正确
          this.detailList = (res.data.inDetailList || []).map(item => ({
            drugId: item.drugId,
            drugName: item.drugName,
            drugGg: item.drugGg,
            drugPZWH: item.drugPZWH || '', // 批准文号 (正确字段名)
            drugBatchNo: item.drugBatchNo || '', // 批次号
            drugNum: item.drugNum || 1, // 数量
            drugCd: item.drugCd || '', // 生产厂家
            drugExp: item.drugExp || '', // 有效期
            drugPd: item.drugPd || '', // 生产日期
            drugDw: item.drugDw || '' // 单位
          }));

          // 重新计算总数（确保数据一致性）
          this.calculateTotals();
        }
      }).catch(error => {
        this.$message.error('加载数据失败：' + error.message);
        // 如果加载失败，回退到新增模式
        this.generateOrderNo();
        this.initFormData();
      });
    },
    //根据状态值获取状态名称
    getBillsStateName(state) {
      const stateMap = {
        '0': '未收货',
        '1': '已收货',
        '2': '已验收',
        '3': '已上架',
        '4': '已作废'
      };
      return stateMap[state] || '未知状态';
    }
  }
}
</script>

<style lang="scss" scoped>
.mt10 {
  margin-top: 10px;
}

.mt20 {
  margin-top: 20px;
}

.w200 {
  width: 200px;
}

.el-table {
  .el-input-number {
    width: 120px;
  }

  .el-date-editor {
    width: 150px;
  }
}
</style>
